package com.zyz.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.zyz.entity.User;
import com.zyz.service.FriendService;
import com.zyz.service.UserService;

public class FriendServlet extends HttpServlet{

	UserService userService = new UserService();
	FriendService friendService = new FriendService();
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		
		String method = request.getParameter("method");
		
		
		if(method.equals("find")){
			findAllFrriends(request,response);
		}
		
		
		if(method.equals("delete")){
			deleteFriends(request,response);
		}
	}

	public void deleteFriends(HttpServletRequest request,
			HttpServletResponse response) {
		
        Integer friendId =Integer.parseInt(request.getParameter("friendId"));
		
		HttpSession session = request.getSession();
		User user=(User) session.getAttribute("user");
		
		friendService.delet(user.getId(), friendId);
		
		findAllFrriends(request,response);
     
	}
	public void findAllFrriends(HttpServletRequest request,
			HttpServletResponse response) {
		 try {
				
				HttpSession session = request.getSession();
				
				User user=(User) session.getAttribute("user");
				
				List<User> listFriends =userService.findAllFriends(user.getId());
				request.setAttribute("listFriends", listFriends);
				request.getRequestDispatcher("/friendList.jsp").forward(request, response);
			}catch (Exception e) {
			e.printStackTrace();
			}
			
		}
}



